/*
 *    Copyright (C) 2016 Amit Shekhar
 *    Copyright (C) 2011 Android Open Source Project
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.networking;

import com.ohosnetworking.OhosNetworking;
import com.ohosnetworking.common.ANRequest;
import com.ohosnetworking.common.Priority;
import com.ohosnetworking.error.ANError;
import com.ohosnetworking.interfaces.DownloadListener;
import com.ohosnetworking.interfaces.JSONObjectRequestListener;
import com.ohosnetworking.interfaces.ParsedRequestListener;
import com.ohosnetworking.interfaces.UploadProgressListener;
import com.networking.bean.JsonDataBean;
import com.networking.utils.ImageUtil;
import com.networking.utils.OkLog;
import com.rxohosnetworking.HosSchedulers;
import com.rxohosnetworking.RxOhosNetworking;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.eventhandler.EventRunner;
import ohos.media.image.PixelMap;
import ohos.utils.zson.ZSONObject;
import rx.Observer;
import rx.schedulers.Schedulers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 网络请求sample
 */
public class MainAbility extends Ability implements Component.ClickedListener {

    private final static String BIG_PICTURE = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2437852064,3906650154&fm=26&gp=0.jpg";
    private final static String DOG_PICTURE = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1606209783552&di=8d6bdca45b7af23a406ccac52a8f1415&imgtype=0&src=http%3A%2F%2Fa4.att.hudong.com%2F27%2F67%2F01300000921826141299672233506.jpg";
    private final static String VIEW_PICTURE = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3651717973,1621948329&fm=26&gp=0.jpg";
    private Text responseDataText;
    private ProgressBar progressBar1;
    private Image downImageView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_layout_base_details);

        downImageView = (Image) findComponentById(ResourceTable.Id_DownImage);
        Button deleteBtn = (Button) findComponentById(ResourceTable.Id_delete);
        Button getBtn = (Button) findComponentById(ResourceTable.Id_get);
        Button postBtn = (Button) findComponentById(ResourceTable.Id_post);
        Button syncGet = (Button) findComponentById(ResourceTable.Id_syncGet);

        Button putBtn = (Button) findComponentById(ResourceTable.Id_put);
        Button patchBtn = (Button) findComponentById(ResourceTable.Id_patch);
        Button downloadBtn = (Button) findComponentById(ResourceTable.Id_download);
        Button uploadJsonGet = (Button) findComponentById(ResourceTable.Id_uploadJson);
        responseDataText = (Text) findComponentById(ResourceTable.Id_responseData);
        progressBar1 = (ProgressBar) findComponentById(ResourceTable.Id_progressBar1);
        deleteBtn.setClickedListener(this);
        getBtn.setClickedListener(this);
        postBtn.setClickedListener(this);
        syncGet.setClickedListener(this);
        putBtn.setClickedListener(this);
        patchBtn.setClickedListener(this);
        downloadBtn.setClickedListener(this);
        uploadJsonGet.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_delete:
                prefetchDownload();
                break;
            case ResourceTable.Id_get:
                prefetch();
                break;
            case ResourceTable.Id_post:
                convertBean();
                break;
            case ResourceTable.Id_syncGet:
                checkForHeaderGet();
                break;
            case ResourceTable.Id_put:
                createPost();
                break;
            case ResourceTable.Id_patch:
                createAnUserJSONObject();
                break;
            case ResourceTable.Id_download:
                uploadImage();
                break;
            case ResourceTable.Id_uploadJson:
                rxJavaGet();
                break;
        }
    }

    private void rxJavaGet() {
        RxOhosNetworking.get(VIEW_PICTURE)
                .addPathParameter("userId", "1")
                .setUserAgent("getAnUser")
                .build()
                .getBitmapObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(HosSchedulers.mainThread())
                .subscribe(new Observer<PixelMap>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }

                    @Override
                    public void onNext(PixelMap pixelMap) {
                        downImageView.setPixelMap(pixelMap);
                    }
                });
    }

    private void prefetch() {
        OhosNetworking.get("https://httpbin.org/get")
                .addPathParameter("pageNumber", "0")
                .addQueryParameter("limit", "3")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(ZSONObject response) {
                        OkLog.e("prefetch---response---" + response.toString());
                        responseDataText.setText(response.toString());
                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });
    }

    private void prefetchDownload() {
        OhosNetworking.download(DOG_PICTURE, getContext().getCacheDir().getAbsolutePath(), "file1.jpg")
                .setTag(this)
                .setPriority(Priority.HIGH)
                .build()
                .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        File file = new File(getContext().getCacheDir().getAbsolutePath(), "file1.jpg");
                        downImageView.setPixelMap(ImageUtil.getPixelMapByFile(file));
                        try {
                            responseDataText.setText(file.getCanonicalPath());
                        } catch (IOException e) {
                            OkLog.e(e.getMessage());
                        }
                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });
    }

    private void convertBean() {
        OhosNetworking.get("https://httpbin.org/get")
                .addPathParameter("userId", "1")
                .setTag(this)
                .setPriority(Priority.LOW)
                .setUserAgent("ConvertBean")
                .build()
                .getAsObject(JsonDataBean.class, new ParsedRequestListener<JsonDataBean>() {
                    @Override
                    public void onResponse(JsonDataBean jsonDataBean) {

                        OkLog.e("onResponse---" + jsonDataBean.toString());
                        responseDataText.setText(jsonDataBean.toString());
                    }

                    @Override
                    public void onError(ANError anError) {
                        // Utils.logError(TAG, anError);
                    }
                });
    }

    private void checkForHeaderGet() {
        ANRequest.GetRequestBuilder getRequestBuilder = new ANRequest.GetRequestBuilder("https://httpbin.org/get");
        getRequestBuilder.addHeaders("token", "1234")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(ZSONObject response) {
                        OkLog.e("onResponse---" + response.toString());
                        responseDataText.setText(response.toString());
                    }

                    @Override
                    public void onError(ANError error) {

                    }
                });
    }

    private void createPost() {
        OhosNetworking.post("https://httpbin.org/post")
                .addBodyParameter("firstname", "Suman")
                .addBodyParameter("lastname", "Shekhar")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(ZSONObject response) {
                        OkLog.e("onResponse object : " + response.toString());
                        responseDataText.setText(response.toString());
                    }

                    @Override
                    public void onError(ANError error) {
                        OkLog.e("onError object : " + error.getErrorDetail());
                    }
                });
    }

    private void createAnUserJSONObject() {
        ZSONObject jsonObject = new ZSONObject();
        jsonObject.put("firstname", "Rohit");
        jsonObject.put("lastname", "Kumar");
        OhosNetworking.post("https://httpbin.org/post")
                .addJSONObjectBody(jsonObject)
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(ZSONObject response) {
                        OkLog.e("onResponse ZSONObject : " + response.toString());
                        responseDataText.setText(response.toString());
                    }

                    @Override
                    public void onError(ANError error) {
                        OkLog.e("onError ZSONObject : " + error.getErrorDetail());
                    }
                });
    }

    private File createTempFile(String namePart, int byteSize) {
        FileOutputStream fos = null;
        try {
            File file = File.createTempFile(namePart, "_handled", getCacheDir());
            fos = new FileOutputStream(file);
            Random random = new Random();
            byte[] buffer = new byte[byteSize];
            random.nextBytes(buffer);
            fos.write(buffer);
            fos.flush();
            fos.close();
            return file;
        } catch (Throwable t) {
            OkLog.e("createTempFile failed" + t.getMessage());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    OkLog.e(e.getMessage());
                }
            }
        }
        return null;
    }

    private void uploadImage() {
        final String key = "image";
        final File file = new File(getContext().getCacheDir().getAbsolutePath(), "file1.jpg");
        OhosNetworking.upload("https://httpbin.org/post")
                .setPriority(Priority.MEDIUM)
                .addMultipartFile("image", createTempFile("ddd.txt", 1024))
                .setTag(this)
                .build()
                .setUploadProgressListener(new UploadProgressListener() {
                    @Override
                    public void onProgress(long bytesUploaded, long totalBytes) {
                        OkLog.e("bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes);
                        OkLog.e("setUploadProgressListener isMainThread : " + String.valueOf(EventRunner.current() == EventRunner.getMainEventRunner()));
                    }
                })
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(ZSONObject response) {
                        responseDataText.setText(response.toString());
                        OkLog.e("uploadImage response : " + response.toString());
                    }

                    @Override
                    public void onError(ANError error) {
                        OkLog.e("uploadImage ANError : " + error.getErrorDetail() + error.getErrorCode() + error.getErrorBody());
                    }
                });
    }
}
